package com.tbvtc.agriculturalcreditchainserver2025.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

    @Bean("blockchainQueryExecutor") // 指定线程池名称
    public Executor blockchainQueryExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数 = 平均并行查询数
        executor.setCorePoolSize(5);
        // 最大线程数 = 高峰时查询数 × 1.5
        executor.setMaxPoolSize(8);
        // 队列容量 = 预估峰值请求量 × 单请求任务数
        executor.setQueueCapacity(1000);
        executor.setThreadNamePrefix("BCOS-Query-");
        // 拒绝策略：由调用线程处理（保障基础功能）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程存活时间（秒）
        executor.setKeepAliveSeconds(30);
        executor.initialize();
        return executor;
    }
}